import ajax from "./module/ajax.js";
import { dateHandler, timeHandler, $toast } from './module/tools.js';

let userData = JSON.parse(localStorage.getItem("userData"));
let dateList = [];
let date = document.querySelector('.date');
let sessionsList = [];
let sessions = document.querySelector('.contentList');
// 获取日期列表
window.onload = async function () {
    if (!userData) location.href = '../index.html';

    let dateRes = await ajax({
        url: 'http://egg.flower.dbice.cn/api/date',
        headers: {
            'x-token': userData.token
        }
    })
    // 筛选出大于现在日期的时间并进行排序
    dateList = dateRes.data
        .filter(item => item.time > +new Date())
        .sort((a, b) => a.time - b.time);
    // 日期渲染
    renderDateList();

    // 获取场次列表
    let sessionsRes = await ajax({
        url: 'http://egg.flower.dbice.cn/api/session',
        data: {
            timeId: dateList[0].id
        },
        headers: {
            'x-token': userData.token
        }
    });
    // 将场次按照时间顺序进行排序
    sessionsList = sessionsRes.data.sort((a, b) => a.start_time - b.start_time);
    renderSessionsList();
}

// 场次预约
sessions.addEventListener('click', async function (e) {
    let id = e.target.dataset.id;
    if (!id || !e.target.dataset.status) return;
    try {
        let appointRes = await ajax({
            url: `http://egg.flower.dbice.cn/api/appointment/${userData.id}`,
            method: 'PUT',
            data: {
                sessionId: id,
                isAppointment: '1'
            },
            headers: {
                'x-token': userData.token
            }
        });

        console.log(appointRes);
        // 将预约信息保存至临时存储
        sessionStorage.setItem("appointment", JSON.stringify(appointRes.data));

        $toast('预约成功', 2000);

        // 2秒后跳转至预约详情页
        setTimeout(function () {
            location.href = '../appointment.html';
        }, 2000);
    } catch (error) {
        $toast(error.msg, 2000);
    }
})

// 日期列表监听
date.addEventListener('change', async function (e) {
    try {
        // 获取当天场次信息
        let sessionsRes = await ajax({
            url: 'http://egg.flower.dbice.cn/api/session',
            data: {
                timeId: e.target.value
            },
            headers: {
                'x-token': userData.token
            }
        });
        // 将场次按照时间顺序进行排序
        sessionsList = sessionsRes.data.sort((a, b) => a.start_time - b.start_time);
        renderSessionsList();
    } catch (error) {
        $toast(error.msg, 2000)
    }
})

// 渲染日期列表
function renderDateList() {
    for (let value of dateList) {
        let oOption = document.createElement('option');
        oOption.value = value.id;
        oOption.innerHTML = dateHandler(value.time);
        date.appendChild(oOption);
    }
}



// 渲染场次列表
function renderSessionsList() {
    // 清空上次列表渲染的信息
    sessions.innerHTML = "";
    // 对场次列表进行遍历渲染
    for (let value of sessionsList) {
        let oLi = document.createElement(`li`);
        oLi.innerHTML = `<p>${timeHandler(value['start_time'])}-${timeHandler(value['end_time'])}</p>
        <p data-id="${value.id}" data-status="${value['is_appointment'] ? true : ''}">${value['is_appointment'] ? '可预约' : '场次已满'}</p>
        `
        sessions.appendChild(oLi);
    }
}